const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const compress = require('compression');

const app = express();
let authority = require('@up/authority');
const oemAuthority = require('@up/oem-authority');
const routes = require('./routes/index');
// const loadData = require('./lib/loadData');
const logger = require('./lib/logger');

app.startAfterConfig = function (appConfig) {
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use(logger.morgan_taf_log());
    app.use(compress());
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));


    // 优品统一登陆
    app.use('/', function (req, res, next) {
        let oemAuthorityHost = appConfig.host.oemauthority_host || '';
        let host = req.hostname;
        let authConfig = { needAuthConfig: true, businessId: '12' };
        let authMidware;// 使用统一登录平台进行登录，并且使用统一登录的权限管理

        if (oemAuthorityHost && host.includes(oemAuthorityHost)) { // oem-authority认证
            authMidware = oemAuthority.auth(authConfig);
        } else {
            authMidware = authority.auth(authConfig);
        }
        if (appConfig.use_ldap === 'yes') {
            authMidware(req, res, next);
        } else if (appConfig.use_ldap === 'no') {
            let userInfo = {
                avatar: 'http://p.qpic.cn/wwhead/nMl9ssowtibVGyrmvBiaibzDqRTOict8ugCZTaLnQOQaKrk0hhr4Z0jibOEZGllx9INL9nFauxXiblC64/0',
                name: 'upchina',
                uid: 'upchina'
            };
            req.userInfo = userInfo;
            res.locals.userInfo = userInfo;
            res.locals.auth = { content: 1 };
            next();
        } else {
            authMidware(req, res, next);
        }
    });


    routes.init(app);
    // catch 404 and forward to error handler
    app.use((req, res, next) => {
        const err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    // error handlers
    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development' || app.get('env') === 'local') {
        app.use((err, req, res) => {
            res.status(err.status || 500);
            res.render('error', {
                message: err.message,
                error: err
            });
        });
    }

    // production error handler
    // no stack traces leaked to user
    app.use((err, req, res) => {
        res.status(err.status || 500);
        res.render('errorFriendly');
    });
};

module.exports = app;
